(ns acst.models.activities
  (:use acst.config.error-config
        acst.config.success-config)
  (:require [acst.models.db :as db]
            [acst.utils.handle-exp :refer [get-error]]
            [acst.utils.sql-util :as sqlutil]
            [acst.utils.escape :refer [html-sanitizer]])
  (:import (java.sql Timestamp)))

(defn find-activity [activity_id]
  (db/query
    (:activities-not-found activities-error)
    ["SELECT create_date, deadline, publisher_id, username , title, content
           FROM activities
           WHERE activity_id = ? AND user_id = publisher_id" activity_id]))


(defn find-all-activity [limit page]
  (db/query (:activities-not-found activities-error)
            [
             "SELECT activity_id, username, create_date, deadline, publisher_id, title, content
            FROM activities, users WHERE user_id = publisher_id
            ORDER BY create_date DESC
            LIMIT ? OFFSET ?" limit (* (- page 1) limit)]))

(defn total-page [limit]
  (sqlutil/find-total-page :activities limit))

(defn insert-activity! [publisher_id deadline title content]
  (let [result (db/insert! :activities
                          (sqlutil/filter-nil
                            {:publisher_id publisher_id
                             :title (html-sanitizer title)
                             :content (html-sanitizer content)
                             :deadline (if (nil? deadline) nil (Timestamp/valueOf deadline))}))]
    (if (get-error result)
      (:insert-activity-failed activities-error)
      result)))

(defn update-activity! [user_id activity_id deadline title content]
  (sqlutil/handle-update!
    user_id
    :activities
    (sqlutil/filter-nil
      {:title (html-sanitizer title)
       :content (html-sanitizer content)
       :deadline (if (nil? deadline) nil (Timestamp/valueOf deadline))})
    ["activity_id = ?" activity_id]
    ["activity_id = ?" activity_id]
    (:update-activity-success activities-result)
    (:update-activity-failed activities-error)))

(defn delete-activity! [activity_id user_id]
  (sqlutil/handle-delete!
    user_id
    :activities
    ["activity_id = ? AND publisher_id = ?" activity_id user_id]
    ["activity_id = ?" activity_id]
    (:delete-activity-success activities-result)
    (:delete-activity-failed activities-error)))